<template>
  <div class="manage-container">

    <div class="tableBar">

      <div class="tableLab" style="text-align: right;">
        <el-button type="primary" style="margin-left: 15px" @click="dialogVisible = true">
          + 新建课程
        </el-button>
      </div>
    </div>
    <el-table :data="tableData" stripe class="data_table">
      <el-table-column prop="courseId" label="课程编号" align="center">
      </el-table-column>
      <el-table-column label="教师名称" align="center">
        <span>{{ userName }}</span>
      </el-table-column>
      <el-table-column prop="courseType" label="课程类型" align="center">
      </el-table-column>
      <el-table-column prop="courseName" label="课程名称" align="center">
      </el-table-column>
      <el-table-column prop="scoreRatio" label="平时分|作业分|小组分(%)" style="width: 25%;"  align="center">
      </el-table-column>
      <el-table-column label="操作" align="center" style="width: 250px;">
        <template slot-scope="scope">
          <el-button type="text" size="small" class="blueBug"
            @click="assignmentHandle(scope.row.courseId, scope.row.teacherId)">
            作业
          </el-button>
          <!-- <el-button type="text" size="small" class="blueBug" @click="questionHandle(scope.row.courseId)">
            题库
          </el-button> -->
          <el-button type="text" size="small" class="blueBug" @click="groudsHandle(scope.row.courseId)">
            小组
          </el-button>
          <el-button type="text" size="small" class="blueBug" @click="editScoreHandle(scope.row.courseId)">
            成绩
          </el-button>
          <el-button type="text" size="small" class="blueBug" @click="editHandle(scope.row.courseId, scope.row)">
            编辑课程
          </el-button>
          <el-button type="text" size="small" class="delBut" @click="deleteHandle(scope.row.courseId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建，修改弹窗 -->
    <div>
      <el-dialog title="输入课程信息" :visible.sync="dialogVisible" width="40%" @close="handleClose" class="messageDialog">
        <div class="input-container">
          <!-- 这里放置你的表单 -->
          <el-form ref="formData" :model="formData" :rules="rules">
            <el-form-item label="选择课程类型" prop="courseType">
              <el-select v-model="formData.courseType" placeholder="请选择课程类型">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="formData.courseName" placeholder="请输入课程名称"></el-input>
            </el-form-item>
          </el-form>
          <div style="margin-bottom: 25px;"><strong>平时分 | 作业分 | 小组分 (%)</strong></div>
          <div class="ratio-container">
            <el-input-number class="item" v-model="atWighting" @change="handleChange" :min="0" :max="100"
              label="平时分"></el-input-number>
            <el-input-number class="item" v-model="asWighting" @change="handleChange" :min="0" :max="100"
              label="作业分"></el-input-number>
            <el-input-number class="item" v-model="exWighting" @change="handleChange" :min="0" :max="100"
              label="小组分"></el-input-number>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="reset()">重置</el-button>
          <el-button type="primary" @click="handleConfirm()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>

import { getTeacherCoursesAPI, addCourseAPI, deleteCourseAPI, editCourseAPI } from '@/api/course'
import { getInfoAPI_Teacher } from '@/api/teacher/personal'
import { getUserIDLocalStorage, getUserNameLocalStorage } from "@/utils/utilLocalStorage";

export default {
  name: 'manage',
  data() {
    return {
      atWighting: '',
      asWighting: '',
      exWighting: '',
      userName: '无',
      dialogVisible: false,
      formData: {
        teacherId: '',
        courseType: '',
        courseName: '',
        scoreRatio: '',
        // courseId: '',
        // 其他需要添加的数据字段
      },
      allid: '',
      options: [{
        value: '公共必修',
        label: '公共必修'
      }, {
        value: '公共选修',
        label: '公共选修'
      }, {
        value: '专业必修',
        label: '专业必修'
      }, {
        value: '专业选修',
        label: '专业选修'
      }, {
        value: '其他',
        label: '其他'
      }],
      tableData: [],
      rules: {
        teacherId: [
          { required: true, message: '请输入教师ID', trigger: 'blur' },
        ],
        courseType: [
          { required: true, message: '请输入课程类型', trigger: 'blur' },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
          { min: 2, max: 15, message: "长度在 2 到 15 个字符", trigger: "blur" }
        ],

      }
    }
  },
  mounted() {
    this.userName = getUserNameLocalStorage()
    this.getCourses()
    this.formData.teacherId = getUserIDLocalStorage()

    // this.getTeacherName()
  },
  methods: {
    //评分占比变化
    handleChange() {
      console.log(this.atWighting, this.asWighting, this.exWighting);
    },
    //关闭新增，修改弹窗
    handleClose() {
      this.dialogVisible = false;
      this.reset() //重置输入内容
      this.getCourses() //更新课程数据,不然只修改内容不确认或取消时,前端列表数据发生改变而后端未改变
    },
    //重置弹窗输入
    reset() {
      // this.formData.courseId = '',
      // this.formData.teacherId = '',
      this.formData.courseType = '',
        this.formData.courseName = ''
      // this.formData.scoreRatio = ''
    },
    //
    questionHandle(courseId) {
      this.$router.push({ path: '/question', query: { courseId: courseId } });
    },
    //编辑小组
    groudsHandle(courseId) {
      this.$router.push({ path: '/groups/getByCourseId', query: { courseId: courseId } });
      // console.log(courseId);
    },
    //发布作业
    assignmentHandle(courseId, teacherId) {
      this.$router.push({ path: '/assignments', query: { courseId: courseId, teacherId: teacherId } });
      // console.log(courseId);
    },
    //编辑学生成绩
    editScoreHandle(courseId) {
      this.$router.push({ path: '/course/gradeRecords/getByCourseId', query: { courseId: courseId } });
      // console.log(courseId);
    },
    //修改按钮
    editHandle(courseId, row) {
      console.log(courseId, row);
      this.dialogVisible = true //显示弹窗
      this.formData = row //将当前行数据赋值给输入框
      //评分占比数组
      const scoreRatios = row.scoreRatio.split("|").map(Number);
      // 分配各分项的占比
      this.atWighting = scoreRatios[0] || 0; // 平时分占比，默认为0
      this.asWighting = scoreRatios[1] || 0; // 作业分占比，默认为0
      this.exWighting = scoreRatios[2] || 0; // 小组分占比（这里可能是指考试分或其他，根据实际情况命名），默认为0
      this.allid = row.courseId //把id存全局
    },
    //确认新增，修改
    handleConfirm() {
      if (this.atWighting + this.asWighting + this.exWighting !== 100) {
        this.$message.error('占比和不等于100%，请重新输入')
        return
      }
      this.formData.scoreRatio = this.atWighting + '|' + this.asWighting + '|' + this.exWighting
      // console.log('1111' + this.formData.scoreRatio);

      // console.log(this.allid);

      if (!this.allid) {
        //新增接口
        console.log(this.formData);
        addCourseAPI(this.formData).then(res => {
          // console.log(res.data);
          if (res.data !== 1) {
            this.$message.error('新增课程失败，请检查输入信息！')
            return
          }
          this.$message.success('新增课程成功！')
          this.getCourses() //刷新页面
          this.reset() //重置输入内容
        })
        this.dialogVisible = false;
      } else {
        // 修改接口
        let courseId = this.allid
        let editData = {
          courseId: this.formData.courseId,
          // teacherId: this.formData.teacherId,
          courseType: this.formData.courseType,
          courseName: this.formData.courseName,
          scoreRatio: this.formData.scoreRatio
        }
        editCourseAPI(courseId, editData).then(res => {
          console.log(res.data);
          if (res.data !== 1) {
            this.$message.success('修改课程失败，请检查输入信息！')
            return
          }
          this.$message.success('修改课程成功！')
          this.reset() //重置输入内容
          this.getCourses() //刷新页面
          this.dialogVisible = false;
        })
      }
    },
    //删除方法
    deleteCourse(courseId) {
      deleteCourseAPI(courseId).then(res => {
        console.log('删除课程：' + courseId);
        if (res.code !== 200) {
          this.$message.error('删除课程失败')
          return
        }
        this.$message.success('删除课程成功')
        this.getCourses()
      })
    },
    //删除按钮
    deleteHandle(courseId) {
      this.$confirm('删除该课程,关于课程的作业、小组也一并删除,确认删除该课程, 是否继续?', '确定删除', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('del');

        this.deleteCourse(courseId)
      })
    },
    getCourses() {
      getTeacherCoursesAPI(getUserIDLocalStorage()).then(res => {
        // 假设后端返回的数据结构中有一个数组可以直接赋值给 tableData
        this.tableData = res.data
      })
        .catch(error => {
          // 处理请求错误
          console.error('请求数据失败:', error);
          // 可以考虑在这里处理用户提示，比如显示一个错误消息
        });
      // console.log(this.tableData);

    },
  }
}
</script>

<style lang="scss" scoped>
/* 自定义类名来调整间距 */
.input-container .el-input {
  margin-bottom: 20px;
  /* 你可以根据需要调整这个值 */
}

.input-container .el-select {
  margin-bottom: 20px;
  /* 你可以根据需要调整这个值 */
}


/* 如果你想要最后一个输入框没有下边距，可以添加一个额外的类名并覆盖它 */
.input-container .el-input:last-child {
  margin-bottom: 0;
}

.ratio-container {
  display: flex;
  /* 使用flex布局 */
  align-items: center;
  /* 垂直居中 */
  justify-content: space-between;
  /* 平均分配间距 */
}

.item {
  flex: 1;
  /* 使每个输入框平均分配空间 */
  margin: 0 10px;
  /* 可选：添加一些间隔 */
}

.ratio-container .item:last-child {
  margin-right: 0;
  /* 清除最后一个元素的右边距 */
}
</style>
